package com.nwpu.ex2_1;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

/**
 * TestInitParams
 *
 * @author 龙虹宇
 * @version 1.0
 * @date 2023/10/14
 */
// @WebServlet(urlPatterns = "/testInitParams", initParams = {
//         @WebInitParam(name = "initParam_1", value = "valueOfInitParam_1"),
//         @WebInitParam(name = "initParam_2", value = "valueOfInitParam_2")
// })
public class TestInitParams extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置response content-type（告诉服务器，传递的是html）以及编码
        response.setContentType("text/html;charset=utf-8");
        // 获取响应字符输出流
        PrintWriter writer = response.getWriter();
        /**
         * 获取 Servlet初始化参数
         */
        // 获取参数名列表
        Enumeration<String> ipn = getServletConfig().getInitParameterNames();
        // 输出
        writer.write("<h3>Servlet初始化参数：</h3><hr>");
        while(ipn.hasMoreElements()) {
            String paramName = ipn.nextElement();
            writer.write(paramName + " = "
                    + getServletConfig().getInitParameter(paramName) + "<hr>");
        }

        /**
         * 获取 Servlet上下文初始参数
         */
        // 获取参数名列表
        Enumeration<String> cipn = getServletContext().getInitParameterNames();
        // 输出
        writer.write("<h3>Servlet上下文初始化参数：</h3><hr>");
        while (cipn.hasMoreElements()) {
            String paramName = cipn.nextElement();
            writer.write(paramName + " = "
                    + getServletContext().getInitParameter(paramName) + "<hr>");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
